using System;
using System.IO;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;

public class ScriptGen : EditorWindow
{
    [MenuItem("Tools/ScriptGen")]
    public static void CreateScriptGen()
    {
        CreateWindow<ScriptGen>().Show();
    }

    private string key = "sk-f6f17dc919d94bc297c998953d7991e4";

    string scriptText = @"Assets/
├── Scripts/
│   ├── Core/                # 框架核心
│   │   ├── Models/          # 数据模型层
│   │   │   ├── IModel.cs
│   │   │   ├── CompositeModel.cs
│   │   │   └── NetworkModel.cs
│   │   ├── Views/           # 渲染层
│   │   │   ├── IView.cs
│   │   │   ├── BaseView.cs
│   │   │   └── Object3DView.cs
│   │   ├── Components/      # 组件化系统
│   │   │   ├── IComponent.cs
│   │   │   └── ComponentContainer.cs
│   │   └── Resources/       # 资源管理
│   │       ├── AddressableManager.cs
│   │       └── ResourceContext.cs
│   ├── Controllers/         # 控制器
│   │   └── PlayerController.cs
│   └── Utils/               # 工具类
│       └── EventSystem.cs
├── Scenes/                  # 示例场景
│   └── DemoScene.unity
└── Addressables/            # Addressables 配置
    └── AssetGroups/
        ├── UI.asset
        └── 3DModels.asset";

    private void OnGUI()
    {
        scriptText = GUILayout.TextArea(scriptText, GUILayout.ExpandHeight(true), GUILayout.Height(400));
        if (GUILayout.Button("Generate"))
        {
            ParseAndGenerateStructure(scriptText);
        }
    }


    private static void ParseAndGenerateStructure(string inputText)
    {
        // 按行分割输入文本
        string[] lines = inputText.Split(new[] { '\n' }, System.StringSplitOptions.RemoveEmptyEntries);

        // 当前路径栈（用于处理嵌套目录）
        var pathStack = new System.Collections.Generic.Stack<string>();

        foreach (string line in lines)
        {
            // 去除行首的空白字符
            string trimmedLine = line.Trim();

            // 跳过空行和注释
            if (string.IsNullOrEmpty(trimmedLine) || trimmedLine.StartsWith("#"))
                continue;
            int indentLevel = 0;
            // 正则表达式模式
            string pattern = @"(│\s*|└──\s|├──\s)";

            // 使用 Regex 查找匹配项
            MatchCollection matches = Regex.Matches(line, pattern);
            
            if (matches.Count > 0)
            {
                int count = 0;
                foreach (var match in matches)
                {
                    string matchStr = match.ToString();

                    if (matchStr.StartsWith(@"│"))
                    {
                        count += (matchStr.Length / 4) - 1;
                    }

                    indentLevel = matches.Count + count;
                }
            }

            // 根据缩进级别调整路径栈
            while (pathStack.Count > indentLevel)
            {
                pathStack.Pop();
            }

            // 提取目录或文件名
            string itemName = ExtractItemName(trimmedLine);

            // 构建完整路径
            string currentPath = pathStack.Count > 0 ? pathStack.Peek() : "";
            string fullPath = Path.Combine(currentPath, itemName);

            // 如果是目录
            if (itemName.EndsWith("/") || itemName.EndsWith("\\"))
            {
                //CreateDirectory(fullPath);
                pathStack.Push(fullPath);
            }
            // 如果是文件
            else
            {
                CreateFile(fullPath);
            }
        }
    }


    private static string ExtractItemName(string line)
    {
        // 提取目录或文件名（去除缩进和特殊字符）
        string itemName = line.Trim();
        itemName = Regex.Replace(itemName, @"[├└│──]", "").Trim();
        itemName = Regex.Replace(itemName, @"[\s]*#[\s\S]*", "").Trim();
        return itemName;
    }

    private static void CreateDirectory(string path)
    {
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
            Debug.Log($"Created directory: {path}");
        }
    }

    private static void CreateFile(string path)
    {
        // Debug.LogError($"{path}");
        // return;
        if (!File.Exists(path))
        {
            string extension = Path.GetExtension(path).ToLower();
            string content = "";

            // 根据文件类型生成默认内容
            switch (extension)
            {
                case ".cs":
                    content = GenerateCSharpClassContent(Path.GetFileNameWithoutExtension(path));
                    break;
                case ".unity":
                    content = "// Unity scene file";
                    return;
                    break;
                case ".asset":
                    content = "// Unity asset file";
                    return;
                    break;
                default:
                    content = "// Default content";
                    return;
                    break;
            }

            if (!Directory.Exists(Path.GetDirectoryName(path)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(path));
            }

            File.WriteAllText(path, content);
            Debug.Log($"Created file: {path}");
        }
    }

    private static string GenerateCSharpClassContent(string className)
    {
        return $@"
using UnityEngine;

public class {className}
{{
}}";
    }
}